package com.lee.taste.spider.sohu.spider;

import java.util.List;

import org.assertj.core.util.Lists;
import org.dom4j.Element;

import com.lee.taste.spider.HttpRequest;
import com.lee.taste.spider.sohu.db.BrandDao;
import com.lee.taste.spider.sohu.entity.Brand;
import com.lee.taste.spider.sohu.entity.SaleBrand;
import com.lee.taste.spider.sohu.xml.XMLParase;
import com.lee.taste.spider.sohu.xml.XMLUtils;

public class BrandSpider {

	private static BrandDao brandDao = new BrandDao();
	public static List<Brand> crawl(String url) throws Exception  {
		String xml = HttpRequest.sendGet(url, "");
		List<Brand> list = parseBrand(XMLParase.parseXml(xml));  
		brandDao.batchUpdateBrand(list);
		return list;
	}
	private static List<Brand>  parseBrand(Element element){
		List<Brand> list = Lists.newArrayList();
		if(element == null){
			return list;
		}
		List<Element> elesBrand = element.elements("brand");
		for(Element e : elesBrand){
			Brand brand = new Brand(XMLUtils.getAttributeValue(e,"id"),XMLUtils.getAttributeValue(e,"name"));
			list.add(brand);
		}
		return list;
	}
	
	public static void crawlSales(String url , Brand brand) throws Exception  {
		String xml = HttpRequest.sendGet(url, "");
		List<SaleBrand> list = parseSales(XMLParase.parseXml(xml),brand);  
		brandDao.batchUpdateBrandSales(list);
	}
	private static List<SaleBrand>  parseSales(Element element, Brand brand){
		List<SaleBrand> list = Lists.newArrayList();
		if(element == null){
			return list;
		}
		List<Element> elesBrand = element.elements("sales");
		for(Element e : elesBrand){
			SaleBrand entity = new SaleBrand(brand.getId(),brand.getName()
					,XMLUtils.getAttributeValue(e,"date"),XMLUtils.getAttributeValue(e,"salesNum"));
			list.add(entity);
		}
		return list;
	}
}
